"use client"

import { Button } from "@/components/ui/button"
import { useState, useEffect } from "react"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Calendar, Plus, ChevronLeft, ChevronRight, ClipboardCheck, AlertCircle } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Calendar as CalendarComponent } from "@/components/ui/calendar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { format } from "date-fns"
import type { SampleFilters, SampleGroup, GroupedPaginatedResponse } from "@/types"

export default function SamplingNumberManagementPage() {
  const [groups, setGroups] = useState<SampleGroup[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedMixedGroups, setSelectedMixedGroups] = useState<string[]>([])
  const [lastSelectedIndex, setLastSelectedIndex] = useState<number | null>(null)
  const [isShiftPressed, setIsShiftPressed] = useState(false)

  // 筛选和分页状态
  const [searchTerm, setSearchTerm] = useState("")
  const [startDate, setStartDate] = useState<Date | undefined>(undefined)
  const [endDate, setEndDate] = useState<Date | undefined>(undefined)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [totalGroups, setTotalGroups] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [totalSamples, setTotalSamples] = useState(0)

  // 对话框状态
  const [showSamplingDialog, setShowSamplingDialog] = useState(false)

  // 统计数据
  const [stats, setStats] = useState({
    mixedOnly: 0,
    mixedGroups: 0,
    samplingGroups: 0,
  })

  // 监听Shift键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Shift") setIsShiftPressed(true)
    }
    const handleKeyUp = (e: KeyboardEvent) => {
      if (e.key === "Shift") setIsShiftPressed(false)
    }

    window.addEventListener("keydown", handleKeyDown)
    window.addEventListener("keyup", handleKeyUp)
    return () => {
      window.removeEventListener("keydown", handleKeyDown)
      window.removeEventListener("keyup", handleKeyUp)
    }
  }, [])

  // 获取只有混合编号的样品数据
  const fetchSamples = async () => {
    setLoading(true)
    try {
      const filters: SampleFilters = {
        search: searchTerm,
        status: "mixed-only", // 只获取有混合编号但无抽检编号的样品
        startDate: startDate?.toISOString(),
        endDate: endDate?.toISOString(),
        page: currentPage,
        pageSize: pageSize,
      }

      const queryParams = new URLSearchParams()
      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== "") {
          queryParams.append(key, value.toString())
        }
      })

      const response = await fetch(`/api/samples?${queryParams}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })

      const result = await response.json()

      if (result.success) {
        const data: GroupedPaginatedResponse = result.data
        setGroups(data.groups)
        setTotalGroups(data.total)
        setTotalPages(data.totalPages)
        setTotalSamples(data.totalSamples)
      }
    } catch (error) {
      console.error("获取样品数据失败:", error)
    } finally {
      setLoading(false)
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const response = await fetch("/api/samples/stats", {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
      const result = await response.json()
      if (result.success) {
        setStats({
          mixedOnly: result.data.mixedOnly,
          mixedGroups: result.data.mixedGroups,
          samplingGroups: result.data.samplingGroups,
        })
      }
    } catch (error) {
      console.error("获取统计数据失败:", error)
    }
  }

  useEffect(() => {
    fetchSamples()
  }, [currentPage, pageSize, searchTerm, startDate, endDate])

  useEffect(() => {
    fetchStats()
  }, [])

  // 处理混合编号组选择
  const handleSelectMixedGroup = (mixedNumber: string, checked: boolean, index: number) => {
    if (isShiftPressed && lastSelectedIndex !== null) {
      const mixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
      const currentMixedIndex = mixedNumbers.indexOf(mixedNumber)
      const lastMixedIndex = lastSelectedIndex

      if (currentMixedIndex !== -1 && lastMixedIndex !== -1) {
        const start = Math.min(lastMixedIndex, currentMixedIndex)
        const end = Math.max(lastMixedIndex, currentMixedIndex)
        const rangeMixedNumbers = mixedNumbers.slice(start, end + 1)
        const newSelected = [...new Set([...selectedMixedGroups, ...rangeMixedNumbers])]
        setSelectedMixedGroups(newSelected)
      }
    } else {
      if (checked) {
        setSelectedMixedGroups([...selectedMixedGroups, mixedNumber])
      } else {
        setSelectedMixedGroups(selectedMixedGroups.filter((id) => id !== mixedNumber))
      }
      const mixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
      const currentIndex = mixedNumbers.indexOf(mixedNumber)
      setLastSelectedIndex(currentIndex)
    }
  }

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      const allMixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
      setSelectedMixedGroups(allMixedNumbers)
    } else {
      setSelectedMixedGroups([])
    }
  }

  // 生成抽检编号
  const generateSamplingNumbers = async () => {
    if (selectedMixedGroups.length === 0) {
      alert("请先选择要生成抽检编号的混合编号组")
      return
    }

    try {
      const response = await fetch("/api/samples/generate-sampling", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
        body: JSON.stringify({
          mixedNumbers: selectedMixedGroups,
        }),
      })

      const result = await response.json()
      if (result.success) {
        alert(result.message)
        setSelectedMixedGroups([])
        setShowSamplingDialog(false)
        fetchSamples()
        fetchStats()
      } else {
        alert(result.message || "生成失败")
      }
    } catch (error) {
      alert("网络错误，请稍后重试")
    }
  }

  const getMixedNumberColor = (mixedNumber: string) => {
    const colors = [
      "bg-blue-100 text-blue-800",
      "bg-green-100 text-green-800",
      "bg-purple-100 text-purple-800",
      "bg-orange-100 text-orange-800",
    ]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return colors[index]
  }

  const getMixedCellBorderStyle = (mixedNumber: string) => {
    const baseStyle = "border-l-4"
    const colors = ["border-blue-300", "border-green-300", "border-purple-300", "border-orange-300"]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return `${baseStyle} ${colors[index]}`
  }

  const allMixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
  const isAllSelected = allMixedNumbers.length > 0 && selectedMixedGroups.length === allMixedNumbers.length
  const isPartialSelected = selectedMixedGroups.length > 0 && selectedMixedGroups.length < allMixedNumbers.length

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <ClipboardCheck className="h-7 w-7 text-green-600" />
            抽检编号管理
          </h1>
          <p className="text-muted-foreground">为已有混合编号的样品生成抽检编号</p>
        </div>
        <Dialog open={showSamplingDialog} onOpenChange={setShowSamplingDialog}>
          <DialogTrigger asChild>
            <Button disabled={selectedMixedGroups.length === 0} className="bg-green-600 hover:bg-green-700">
              <Plus className="w-4 h-4 mr-2" />
              生成抽检编号 ({selectedMixedGroups.length})
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>生成抽检编号</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  已选择 {selectedMixedGroups.length} 个混合编号组，将生成 1 个抽检编号。
                  <br />
                  选中的混合编号组：{selectedMixedGroups.join(", ")}
                </AlertDescription>
              </Alert>
              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setShowSamplingDialog(false)}>
                  取消
                </Button>
                <Button onClick={generateSamplingNumbers} className="bg-green-600 hover:bg-green-700">
                  确认生成
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="border-l-4 border-yellow-400">
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">待抽检样品数</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">{stats.mixedOnly}</div>
            <div className="text-xs text-muted-foreground mt-1">仅有混合编号的样品</div>
          </CardContent>
        </Card>
        <Card className="border-l-4 border-blue-400">
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">可抽检组数</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{stats.mixedGroups - stats.samplingGroups}</div>
            <div className="text-xs text-muted-foreground mt-1">等待生成抽检编号</div>
          </CardContent>
        </Card>
        <Card className="border-l-4 border-green-400">
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">已选择组数</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{selectedMixedGroups.length}</div>
            <div className="text-xs text-muted-foreground mt-1">
              {selectedMixedGroups.length > 0 && "将生成 1 个抽检编号"}
            </div>
          </CardContent>
        </Card>
        <Card className="border-l-4 border-purple-400">
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">当前页样品数</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">{totalSamples}</div>
            <div className="text-xs text-muted-foreground mt-1">本页显示的样品数量</div>
          </CardContent>
        </Card>
      </div>

      {/* 搜索和筛选条件 */}
      <div className="flex gap-4 items-center flex-wrap">
        <Input
          placeholder="搜索样品编号、名称..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="w-64"
        />

        <Popover>
          <PopoverTrigger asChild>
            <Button variant="outline" size="icon">
              <Calendar className="h-4 w-4" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-auto p-0" align="end">
            <div className="p-3 border-b">
              <div className="text-sm font-medium">操作时间范围</div>
            </div>
            <div className="p-3 flex flex-col gap-2">
              <div>
                <div className="text-xs mb-1">开始日期</div>
                <CalendarComponent
                  mode="single"
                  selected={startDate}
                  onSelect={setStartDate}
                  className="border rounded-md"
                />
              </div>
              <div>
                <div className="text-xs mb-1">结束日期</div>
                <CalendarComponent
                  mode="single"
                  selected={endDate}
                  onSelect={setEndDate}
                  className="border rounded-md"
                />
              </div>
              <div className="flex justify-end">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setStartDate(undefined)
                    setEndDate(undefined)
                  }}
                >
                  重置
                </Button>
              </div>
            </div>
          </PopoverContent>
        </Popover>

        <Select value={pageSize.toString()} onValueChange={(value) => setPageSize(Number(value))}>
          <SelectTrigger className="w-32">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="5">5组/页</SelectItem>
            <SelectItem value="10">10组/页</SelectItem>
            <SelectItem value="20">20组/页</SelectItem>
            <SelectItem value="50">50组/页</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* 样品表格 */}
      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600"></div>
            </div>
          ) : totalSamples === 0 ? (
            <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
              <ClipboardCheck className="h-12 w-12 mb-4" />
              <p className="text-lg font-medium">暂无待抽检样品</p>
              <p className="text-sm">所有混合编号组都已生成抽检编号</p>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-100">
                    <TableHead className="w-12">
                      <Checkbox
                        checked={isAllSelected}
                        data-indeterminate={isPartialSelected}
                        onCheckedChange={handleSelectAll}
                      />
                    </TableHead>
                    <TableHead>混合编号</TableHead>
                    <TableHead>样品编号</TableHead>
                    <TableHead>样品名称</TableHead>
                    <TableHead>样品类型</TableHead>
                    <TableHead>送检单位</TableHead>
                    <TableHead>操作人</TableHead>
                    <TableHead>操作时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {groups.map((group) => {
                    const mixedNumber = group.mixedNumber!
                    const isSelected = selectedMixedGroups.includes(mixedNumber)

                    return group.samples.map((sample, sampleIndex) => {
                      const showMixedCell = sampleIndex === 0
                      const showCheckbox = sampleIndex === 0

                      return (
                        <TableRow
                          key={sample.id}
                          className={isSelected ? "bg-green-50" : "bg-yellow-50 hover:bg-yellow-100"}
                        >
                          <TableCell>
                            {showCheckbox && (
                              <Checkbox
                                checked={isSelected}
                                onCheckedChange={(checked) =>
                                  handleSelectMixedGroup(mixedNumber, checked as boolean, sampleIndex)
                                }
                              />
                            )}
                          </TableCell>
                          {showMixedCell && (
                            <TableCell
                              rowSpan={group.samples.length}
                              className={`align-middle ${getMixedCellBorderStyle(mixedNumber)}`}
                            >
                              <Badge variant="secondary" className={getMixedNumberColor(mixedNumber)}>
                                {mixedNumber}
                              </Badge>
                            </TableCell>
                          )}
                          <TableCell className="font-mono text-sm">{sample.sampleNumber}</TableCell>
                          <TableCell>{sample.sampleName}</TableCell>
                          <TableCell>{sample.sampleType}</TableCell>
                          <TableCell>{sample.testingUnit}</TableCell>
                          <TableCell>{sample.operator || "-"}</TableCell>
                          <TableCell>
                            {sample.operationTime ? format(new Date(sample.operationTime), "yyyy-MM-dd HH:mm") : "-"}
                          </TableCell>
                        </TableRow>
                      )
                    })
                  })}
                </TableBody>
              </Table>

              {/* 分页控件 */}
              <div className="flex items-center justify-between px-6 py-4 border-t">
                <div className="text-sm text-muted-foreground">
                  显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, totalGroups)} 组，共{" "}
                  {totalGroups} 个混合编号组 ({totalSamples} 个样品)
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                    disabled={currentPage === 1}
                  >
                    <ChevronLeft className="h-4 w-4" />
                    上一页
                  </Button>
                  <div className="flex items-center gap-1">
                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      let pageNum
                      if (totalPages <= 5) {
                        pageNum = i + 1
                      } else if (currentPage <= 3) {
                        pageNum = i + 1
                      } else if (currentPage >= totalPages - 2) {
                        pageNum = totalPages - 4 + i
                      } else {
                        pageNum = currentPage - 2 + i
                      }

                      return (
                        <Button
                          key={pageNum}
                          variant={currentPage === pageNum ? "default" : "outline"}
                          size="sm"
                          onClick={() => setCurrentPage(pageNum)}
                          className="w-8 h-8 p-0"
                        >
                          {pageNum}
                        </Button>
                      )
                    })}
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                    disabled={currentPage === totalPages}
                  >
                    下一页
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* 操作说明 */}
      <Card>
        <CardContent className="p-4">
          <div className="text-sm space-y-2">
            <div>
              <strong>操作说明：</strong>
            </div>
            <ul className="list-disc list-inside space-y-1 text-muted-foreground">
              <li>选择需要生成抽检编号的混合编号组，可以使用Shift键进行范围选择</li>
              <li>每个混合编号组包含多个样品，选择时以组为单位</li>
              <li>点击"生成抽检编号"按钮，系统将为选中的所有混合编号组生成一个统一的抽检编号</li>
              <li>生成后的样品将完成整个编号流程，可在样品概览页面查看完整状态</li>
            </ul>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
